package com.youpai.platform.vulture.service.util;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @date: 2022/7/9 12:50
 * @author: Anna
 * @version: 1.0
 * @description: channelId生成工具类
 */
@Slf4j
public class ChannelIdGeneratorUtil {

    private static final String CHANNEL_ID_SEPARATOR = "|";

    private static final AtomicInteger SEQ = new AtomicInteger();

    public static String generateChannelId(Channel channel) {
        if (null == channel) {
            throw new IllegalStateException("channel 为空");
        }
        SocketAddress remoteAddress = channel.remoteAddress();
        StringBuilder sb = new StringBuilder(96);
        sb.append(NetUtil.getLocalIpAddress());
        sb.append(CHANNEL_ID_SEPARATOR);
        if (remoteAddress instanceof InetSocketAddress) {
            InetSocketAddress inetSocketAddress = (InetSocketAddress) remoteAddress;
            sb.append(inetSocketAddress.getAddress())
                    .append(CHANNEL_ID_SEPARATOR)
                    .append(inetSocketAddress.getPort())
                    .append(CHANNEL_ID_SEPARATOR);
        } else {
            log.error("获取客户端IP端口失败，class - {}, addr - {}", remoteAddress.getClass(), remoteAddress);
            throwIllegalStateException("获取客户端IP端口失败, class=" + remoteAddress.getClass() + ", addr=" + remoteAddress);
        }
        sb.append(System.currentTimeMillis())
                .append(CHANNEL_ID_SEPARATOR)
                .append(Integer.toHexString(SEQ.getAndIncrement()));
        return sb.toString();
    }

    private static void throwIllegalStateException(String msg) {
        IllegalStateException e = new IllegalStateException(msg);
        log.error(msg, e);
        throw e;
    }

}
